package org.mspring.mlog.security.login;

import org.apache.commons.lang3.StringUtils;
import org.mspring.mlog.entity.User;
import org.mspring.mlog.security.SecurityKeys;
import org.mspring.mlog.security.service.UserService;
import org.mspring.nbee.common.utils.RequestUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Gao Youbo
 * @since 2014-09-10 17:25:42
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    public static final String USERNAME_PARAM = "username";
    public static final String PASSWORD_PARAM = "password";

    private UserService userService;
    private UserDetailsService userDetailsService;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!StringUtils.equalsIgnoreCase(request.getMethod(), RequestMethod.POST.name())) {
            throw new AuthenticationServiceException("请求类型错误。");
        }
        String username = RequestUtils.getRequiredParam(request, USERNAME_PARAM);
        String password = RequestUtils.getRequiredParam(request, PASSWORD_PARAM);
        User loginUser = userService.login(username, password);
        if (loginUser == null) {
            throw new AuthenticationServiceException("登录失败，用户名或密码错误");
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
        setDetails(request, authentication);
        request.getSession().setAttribute(SecurityKeys.CURRENT_USER, loginUser);
        return authentication;
    }


    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
